#!/bin/sh
cd /app/client

update_config()
{
  if [ -e /tmp/config ] ; then
    . /tmp/config
    mv /tmp/config /tmp/configold
  fi
  export VIDEO_OUTPUT
  export VIDEO_RESOLUTION
  export AUDIO_OUTPUT
  export VIDEO_SUPPORTED_MODES
  export CACHED_AUTH
  export SERVER_NAME
}

update_server()
{
  SERVER=127.0.0.1
  if [ -e /config/uitype ] ; then
    read uimode uiserver uires uiremote < /config/uitype
    if [ "$uimode" = "extender" ] ; then
      if [ "$uiserver" = "auto" ] ; then
        SERVER=/app/client/miniclient
      else
        SERVER=$uiserver
      fi
      [ -n "$uires" ] && export VIDEO_RESOLUTION=$uires
      [ -n "$uiremote" ] && export RCMODE=$uiremote
    fi
  fi
}

export LD_LIBRARY_PATH=/app/client:/usr/local/lib:$LD_LIBRARY_PATH
export DRM_BIN_FILE=/user/widevine/drm.bin
export SERIALNUMBER=$(cat /etc/serial)

ulimit -c 49152

SERVER_MAC=
opts=
# TV box starts in last mode before power off
if [ -e /rw/sage/TVUIon ] ; then
  mode=miniclient
else
  mode=waitpower
fi
if [ -e /tmp/runapp ] ; then
  mode=app
  read appname opts </tmp/runapp
  # For now don't let opts through
  opts=
  if [ "$appname" = "miniclient" ]; then
    mode=miniclient
    mv /tmp/runapp /tmp/runappold
  fi
fi


update_server
SERVER_MAC=

while :; do
  update_config  # may change $SERVER or other things
  echo "$0: mode: '$mode'"
  case "$mode" in
    miniclient)
      rm -f /tmp/gpio/ledcontrol/waitpower
      [ -n "$SERVER_MAC" ] && [ ! -e /tmp/goalone ] && ether-wake $SERVER_MAC
      # miniclient is realtime sensitive, so run it on second CPU
      try_taskset 2 ./miniclient $opts "$SERVER"
      mcstate=$?
      update_server
      if [ "$mcstate" != "0" ]; then
        echo "Unexpected exit, miniclient restarting after a delay"
        sleep 10  # prevent high-speed spinning in a loop
      elif [ -e /tmp/runapp ] ; then
        mode=app
      else
        mode=waitpower
      fi
      ;;
    app)
      mv /tmp/runapp /tmp/runappold
      rm -f /tmp/gpio/ledcontrol/waitpower
      ./run-app
      if [ -e /tmp/poweroff ] ; then
        mode=waitpower
        rm -f /tmp/poweroff
      else
        mode=miniclient
      fi
      ;;
    waitpower)
      echo > /tmp/gpio/ledcontrol/waitpower
      ./waitpower 2>&1 | logos waitpower
      mode=miniclient
      ;;
  esac
done
